import {
    isFunction
} from "./utils"
import {
    updateTextNode
} from './update'
import updateNodeElement from './updateNodeElement'
import diffComponent from "./diffComponent"
import {
    mountElement
} from "./mount"
import {unMountNode} from './dom'

export default function diff(virtualDOM, container, oldDOM) {
    if (!oldDOM) {
        mountElement(virtualDOM, container)
    } else {
        const oldVirtualDOM = oldDOM.__virtualDOM
        if (virtualDOM.type === oldVirtualDOM.type) {
            if (virtualDOM.type === 'text') {
                updateTextNode(virtualDOM, oldVirtualDOM, oldDOM)
            } else {
                updateNodeElement(oldDOM, virtualDOM, oldVirtualDOM)
            }
            virtualDOM.children.forEach((child, i) => {
                diff(child, oldDOM, oldDOM.childNodes[i])
            })
            let oldChildNodes = oldDOM.childNodes
            if (oldChildNodes.length > virtualDOM.children.length) {
                for (let len = virtualDOM.children.length - 1, i = oldChildNodes.length - 1; i > len; i--) {
                    unMountNode(oldChildNodes[i])
                }
            }
        } else if (!isFunction(virtualDOM)) {
            // 节点不同并且不是组件
            const newEl = createDOMElement(virtualDOM)
            container.replaceChild(newEl, oldDOM)
        } else {
            diffComponent(virtualDOM, oldVirtualDOM, oldDOM, container)
        }
    }
}